package tcakes.ccrefactoring;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.NoSuchElementException;

public class StringArrayArgumentMarshaler implements ArgumentMarshaler {
    private ArrayList<String> stringArrayListValue = new ArrayList<String>();

    public void set(ListIterator<String> currentArgument) throws ArgsException {
        try {
            do {
                String possibleListElement = currentArgument.next();
                if(possibleListElement.charAt(0) != '-') {
                    stringArrayListValue.add(possibleListElement);
                } else {
                    currentArgument.previous();
                    if(stringArrayListValue.size() == 0) {
                        throw new NoSuchElementException();
                    }
                    return;
                }
            } while(currentArgument.hasNext());
        } catch (NoSuchElementException e) {
            throw new ArgsException(ArgsException.ErrorCode.MISSING_STRING_ARRAY);
        }
    }

    public static String[] getValue(ArgumentMarshaler am) {
        if (am != null && am instanceof StringArrayArgumentMarshaler) {
            String[] stringArrayValue = new String[0];
            stringArrayValue = ((StringArrayArgumentMarshaler) am).stringArrayListValue.toArray(stringArrayValue);
            return stringArrayValue;
        } else {
            return new String[]{};
        }
    }
}
